using AntdUI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.DirectoryServices.ActiveDirectory;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TangLiveRecorder.Models;
using TangLiveRecorder.Services;
using static TangLiveRecorder.Data;

namespace TangLiveRecorder.Controls
{
    public partial class LiveControl : UserControl, ITransient
    {
        private Form _form;

        public LiveControl(MainWindow form)
        {
            InitializeComponent();
            this.Tag = "Live";
            this.Dock = DockStyle.Fill;
            this.panelLiveList.Gap = 15;
            LoadData();
            _form = form;
        }

        private void LoadData()
        {
            foreach (var item in Data.GetAllLives())
            {
                AntdUI.VirtualItem virtualItem = new VItem(new IList(item));

                panelLiveList.Items.Add(virtualItem);
            }
            Data.LiveUpdated += Data_LiveUpdated;
        }

        private void Data_LiveUpdated(object? sender, LiveEventArgs e)
        {
            panelLiveList.Items.Clear();
            foreach (var item in Data.GetAllLives())
            {
                AntdUI.VirtualItem virtualItem = new VItem(new IList(item));

                panelLiveList.Items.Add(virtualItem);
            }
            // 触发重绘
            this.panelLiveList.Invalidate();
        }

        private void btnAddLive_Click(object sender, EventArgs e)
        {
            var addLiveControl = App.GetRequiredService<AddLiveControl>();
            AntdUI.Modal.open(new AntdUI.Modal.Config(this._form, "添加", addLiveControl)
            {
                OnOk = Config =>
                {
                    if (string.IsNullOrEmpty(addLiveControl.NickName))
                    {
                        AntdUI.Message.Config config = new AntdUI.Message.Config(this._form, "主播昵称不可为空", TType.Warn);
                        config.ShowInWindow = true;
                        config.open();
                        return false;
                    }
                    if (string.IsNullOrEmpty(addLiveControl.Url))
                    {
                        AntdUI.Message.Config config = new AntdUI.Message.Config(this._form, "直播地址不可为空", TType.Warn);
                        config.ShowInWindow = true;
                        config.open();
                        return false;
                    }

                    var item = new LiveInfo()
                    {
                        Guid = System.Guid.NewGuid().ToString(),
                        Avatar = "https://example.com/avatar.jpg",
                        Name = addLiveControl.NickName,
                        Description = addLiveControl.Description,
                        Url = addLiveControl.Url,
                        Status = false
                    };

                    // 使用Data.AddLive方法添加数据，确保持久化
                    Data.AddLive(item);

                    AntdUI.VirtualItem virtualItem = new VItem(new IList(item));
                    AddLog("添加直播间：" + item.ToString());
                    panelLiveList.Items.Add(virtualItem);
                    return true;
                }
            });
        }

        private class IList : LiveInfo
        {
            public IList()
            { }

            public IList(LiveInfo item)
            {
                this.Guid = item.Guid;
                this.Avatar = item.Avatar;
                this.Name = item.Name;
                this.Description = item.Description;
                this.Url = item.Url;
                this.Status = item.Status;
                this.IsLive = item.IsLive;
                this.IsRecording = item.IsRecording;
            }
        }

        private class VItem : AntdUI.VirtualShadowItem
        {
            public IList data;

            public VItem(IList d)
            {
                data = d;
            }

            private StringFormat s_f = AntdUI.Helper.SF(lr: StringAlignment.Near);
            private StringFormat s_f_wrap = AntdUI.Helper.SF(lr: StringAlignment.Near, tb: StringAlignment.Near);

            public override void Paint(AntdUI.Canvas g, AntdUI.VirtualPanelArgs e)
            {
                // 绘制背景和边框
                var bgColor = data.Status ? AntdUI.Style.Db.BgContainer : Color.FromArgb(250, 250, 250);
                using (var brush = new SolidBrush(bgColor))
                {
                    using (var path = AntdUI.Helper.RoundPath(e.Rect, e.Radius))
                    {
                        g.Fill(brush, path);
                        using (var brush_bor = new Pen(Hover ? AntdUI.Style.Db.BorderColorDisable : AntdUI.Style.Db.BorderColor, thickness))
                        {
                            g.Draw(brush_bor, path);
                        }
                    }
                }

                // 如果禁用状态，添加半透明遮罩
                if (!data.Status)
                {
                    using (var brush = new SolidBrush(Color.FromArgb(128, 255, 255, 255)))
                    {
                        using (var path = AntdUI.Helper.RoundPath(e.Rect, e.Radius))
                        {
                            g.Fill(brush, path);
                        }
                    }
                }

                // 绘制开关
                switchRect = new Rectangle(e.Rect.X + e.Rect.Width - close_button_size - size - switch_width - size, e.Rect.Y + size, switch_width, switch_height);

                // 绘制开关背景
                using (var brush = new SolidBrush(data.Status ? Color.FromArgb(24, 144, 255) : Color.FromArgb(217, 217, 217)))
                {
                    using (var path = AntdUI.Helper.RoundPath(switchRect, switch_height / 2))
                    {
                        g.Fill(brush, path);
                    }
                }

                // 绘制开关滑块
                int sliderSize = switch_height - 4;
                int sliderX = data.Status ? switchRect.X + switch_width - sliderSize - 2 : switchRect.X + 2;
                var sliderRect = new Rectangle(sliderX, switchRect.Y + 2, sliderSize, sliderSize);
                using (var brush = new SolidBrush(Color.White))
                {
                    g.FillEllipse(brush, sliderRect);
                }

                // 绘制关闭按钮
                closeButtonRect = new Rectangle(e.Rect.X + e.Rect.Width - close_button_size - size, e.Rect.Y + size, close_button_size, close_button_size);
                using (var brush = new SolidBrush(Color.FromArgb(255, 77, 79))) // 红色关闭按钮
                {
                    using (var path = AntdUI.Helper.RoundPath(closeButtonRect, close_button_size / 2))
                    {
                        g.Fill(brush, path);
                    }
                }

                // 绘制关闭按钮的 X 符号
                using (var pen = new Pen(Color.White, 2))
                {
                    int margin = 4;
                    g.DrawLine(pen,
                        closeButtonRect.X + margin, closeButtonRect.Y + margin,
                        closeButtonRect.X + closeButtonRect.Width - margin, closeButtonRect.Y + closeButtonRect.Height - margin);
                    g.DrawLine(pen,
                        closeButtonRect.X + closeButtonRect.Width - margin, closeButtonRect.Y + margin,
                        closeButtonRect.X + margin, closeButtonRect.Y + closeButtonRect.Height - margin);
                }

                int currentY = e.Rect.Y + size;

                // 第一行：平台图标 + 平台名称
                var platformIconRect = new Rectangle(e.Rect.X + size, currentY, platform_icon_size, platform_icon_size);

                // 绘制平台图标
                if (!string.IsNullOrEmpty(data.PlatformIcon))
                {
                    var iconColor = data.Status ? AntdUI.Style.Db.Primary : Color.FromArgb(190, 190, 190);
                    var iconBitmap = AntdUI.SvgExtend.SvgToBmp(data.PlatformIcon, platform_icon_size, platform_icon_size, iconColor);
                    if (iconBitmap != null)
                    {
                        g.Image(iconBitmap, platformIconRect);
                    }
                    else
                    {
                        // 如果图标加载失败，显示默认的颜色块
                        using (var brush = new SolidBrush(iconColor))
                        {
                            using (var path = AntdUI.Helper.RoundPath(platformIconRect, 4))
                            {
                                g.Fill(brush, path);
                            }
                        }
                    }
                }
                else
                {
                    // 没有图标时显示默认的颜色块
                    var iconColor = data.Status ? AntdUI.Style.Db.Primary : Color.FromArgb(190, 190, 190);
                    using (var brush = new SolidBrush(iconColor))
                    {
                        using (var path = AntdUI.Helper.RoundPath(platformIconRect, 4))
                        {
                            g.Fill(brush, path);
                        }
                    }
                }

                var textColor = data.Status ? AntdUI.Style.Db.Text : Color.FromArgb(140, 140, 140);
                using (var fore = new SolidBrush(textColor))
                {
                    using (var font_platform = new Font(e.Panel.Font.FontFamily, 10F, FontStyle.Bold))
                    {
                        var platformRect = new Rectangle(e.Rect.X + size + platform_icon_size + size, currentY,
                            e.Rect.Width - size - platform_icon_size - size2, line_height);

                        // 测量平台名称的宽度
                        var platformSize = g.MeasureString(data.Platform, font_platform);

                        // 绘制平台名称
                        g.String(data.Platform, font_platform, fore, platformRect, s_f);

                        // 如果正在直播，在平台名称后绘制"正在直播"标识
                        var currentTextX = platformRect.X + (int)platformSize.Width;
                        if (data.IsLive)
                        {
                            var liveText = " 正在直播";
                            var liveColor = Color.FromArgb(255, 77, 79); // 醒目的红色
                            using (var liveBrush = new SolidBrush(liveColor))
                            {
                                using (var font_live = new Font(e.Panel.Font.FontFamily, 9F, FontStyle.Bold))
                                {
                                    var liveRect = new Rectangle(currentTextX, currentY,
                                        platformRect.Width - (int)platformSize.Width, line_height);
                                    g.String(liveText, font_live, liveBrush, liveRect, s_f);

                                    // 更新X位置，为录制状态预留空间
                                    var liveTextSize = g.MeasureString(liveText, font_live);
                                    currentTextX += (int)liveTextSize.Width;
                                }
                            }
                        }

                        // 如果正在录制，在"正在直播"后绘制"录制中"标识
                        if (data.IsRecording)
                        {
                            var recordText = " 录制中";
                            var recordColor = Color.FromArgb(82, 196, 26); // 绿色
                            using (var recordBrush = new SolidBrush(recordColor))
                            {
                                using (var font_record = new Font(e.Panel.Font.FontFamily, 9F, FontStyle.Bold))
                                {
                                    var recordRect = new Rectangle(currentTextX, currentY,
                                        platformRect.Width - (currentTextX - platformRect.X), line_height);
                                    g.String(recordText, font_record, recordBrush, recordRect, s_f);
                                }
                            }
                        }
                    }
                }

                currentY += line_height + size;

                // 分割线
                using (var brush = new SolidBrush(AntdUI.Style.Db.Split))
                {
                    g.Fill(brush, new RectangleF(e.Rect.X + size, currentY - thickness / 2F,
                        e.Rect.Width - size2, thickness));
                }

                currentY += size;

                // 第二行：头像 + 昵称 + "的直播间"
                var avatarRect = new Rectangle(e.Rect.X + size, currentY, avatar_size, avatar_size);

                // 绘制头像（暂时使用默认用户图标）
                var avatarColor = data.Status ? AntdUI.Style.Db.Primary : Color.FromArgb(190, 190, 190);
                var avatarIcon = AntdUI.SvgExtend.SvgToBmp("UserOutlined", avatar_size, avatar_size, avatarColor);
                if (avatarIcon != null)
                {
                    using (var path = AntdUI.Helper.RoundPath(avatarRect, avatar_size / 2))
                    {
                        g.Image(avatarIcon, avatarRect);
                    }
                }
                else
                {
                    // 如果图标加载失败，显示默认的圆形颜色块
                    using (var brush = new SolidBrush(avatarColor))
                    {
                        using (var path = AntdUI.Helper.RoundPath(avatarRect, avatar_size / 2))
                        {
                            g.Fill(brush, path);
                        }
                    }
                }

                using (var fore = new SolidBrush(textColor))
                {
                    using (var font_name = new Font(e.Panel.Font.FontFamily, 11F, FontStyle.Bold))
                    {
                        var nameRect = new Rectangle(e.Rect.X + size + avatar_size + size, currentY,
                            e.Rect.Width - size - avatar_size - size2, line_height);
                        g.String(data.Name + "的直播间", font_name, fore, nameRect, s_f);
                    }
                }

                currentY += Math.Max(avatar_size, line_height) + size;

                // 第三行：描述
                var descColor = data.Status ? AntdUI.Style.Db.TextSecondary : Color.FromArgb(160, 160, 160);
                using (var fore = new SolidBrush(descColor))
                {
                    using (var font_desc = new Font(e.Panel.Font.FontFamily, 9F))
                    {
                        var descRect = new Rectangle(e.Rect.X + size, currentY,
                            e.Rect.Width - size2, desc_height);
                        g.String(data.Description, font_desc, fore, descRect, s_f_wrap);
                    }
                }

                currentY += desc_height + size;

                // 第四行：链接
                Color urlColor;
                if (isUrlHover)
                {
                    // 悬停时的颜色
                    urlColor = data.Status ? AntdUI.Style.Db.Primary : Color.FromArgb(100, 149, 237);
                }
                else
                {
                    // 正常状态的颜色
                    urlColor = data.Status ? AntdUI.Style.Db.TextTertiary : Color.FromArgb(180, 180, 180);
                }

                using (var fore = new SolidBrush(urlColor))
                {
                    using (var font_url = new Font(e.Panel.Font.FontFamily, 8F, isUrlHover ? FontStyle.Underline : FontStyle.Regular))
                    {
                        urlRect = new Rectangle(e.Rect.X + size, currentY,
                            e.Rect.Width - size2, line_height);
                        g.String(data.Url, font_url, fore, urlRect, s_f);
                    }
                }
            }

            private int thickness = 1, size = 10, size2 = 20;
            private int platform_icon_size = 20, avatar_size = 32, line_height = 24, desc_height = 60, close_button_size = 20;
            private int switch_width = 40, switch_height = 20;

            private Rectangle closeButtonRect; // 存储关闭按钮区域，供点击事件使用
            private Rectangle switchRect; // 存储开关区域，供点击事件使用
            private Rectangle urlRect; // 存储链接区域，供点击事件使用
            private bool isUrlHover = false; // 跟踪链接悬停状态

            public override Size Size(AntdUI.Canvas g, AntdUI.VirtualPanelArgs e)
            {
                var dpi = AntdUI.Config.Dpi;
                thickness = (int)(1 * dpi);
                size = (int)(10 * dpi);
                size2 = size * 2;
                platform_icon_size = (int)(20 * dpi);
                avatar_size = (int)(32 * dpi);
                line_height = (int)(24 * dpi);
                desc_height = (int)(60 * dpi);
                close_button_size = (int)(20 * dpi);
                switch_width = (int)(40 * dpi);
                switch_height = (int)(20 * dpi);

                // 计算总高度：上边距 + 平台行 + 间距 + 分割线间距 + 头像行 + 间距 + 描述 + 间距 + 链接 + 下边距
                int totalHeight = size + line_height + size + size + Math.Max(avatar_size, line_height) + size + desc_height + size + line_height + size;
                return new Size((int)(300 * dpi), totalHeight);
            }

            public override void MouseClick(VirtualPanel sender, VirtualPanelMouseArgs e)
            {
                // 检查是否点击了关闭按钮
                if (closeButtonRect.Contains(e.Location))
                {
                    // 弹出确认删除的模态框
                    AntdUI.Modal.open(new AntdUI.Modal.Config(sender.FindForm(), "确认删除", "确定要删除这个直播间吗？")
                    {
                        Icon = AntdUI.TType.Warn,
                        OkText = "确定",
                        CancelText = "取消",
                        OnOk = (Config) =>
                        {
                            // 用户确认删除，从数据中删除并从面板中移除当前项
                            Data.RemoveLive(data.Guid);
                            sender.Items.Remove(this);
                            return true;
                        }
                    });
                    return;
                }

                // 检查是否点击了开关
                if (switchRect.Contains(e.Location))
                {
                    if (data.Status && data.IsRecording)
                    {
                        AntdUI.Modal.open(new AntdUI.Modal.Config(sender.FindForm(), "确认停止", "直播正在录制，是否停止录制并停止？")
                        {
                            Icon = AntdUI.TType.Warn,
                            OkText = "确定",
                            CancelText = "取消",
                            OnOk = (Config) =>
                            {
                                data.IsRecording = false;
                                var recordingService = App.GetRequiredService<RecordingService>();
                                recordingService.StopRecordingAsync(data.Guid);
                                return true;
                            }
                        });
                    }
                    else
                    {
                    }
                    // 切换状态
                    data.Status = !data.Status;
                    // 更新数据并持久化
                    var updatedLive = new LiveInfo()
                    {
                        Guid = data.Guid,
                        Avatar = data.Avatar,
                        Name = data.Name,
                        Description = data.Description,
                        Url = data.Url,
                        Status = data.Status,
                        IsRecording = data.IsRecording
                    };
                    Data.UpdateLive(updatedLive);
                    // 触发重绘
                    sender.Invalidate();
                    return;
                }

                // 检查是否点击了链接
                if (urlRect.Contains(e.Location))
                {
                    try
                    {
                        // 复制链接到剪贴板
                        Clipboard.SetText(data.Url);
                        // 显示复制成功提示
                        AntdUI.Message.success(sender.FindForm(), "链接已复制到剪贴板", autoClose: 2);
                    }
                    catch
                    {
                        // 复制失败提示
                        AntdUI.Message.error(sender.FindForm(), "复制链接失败", autoClose: 2);
                    }
                    return;
                }

                base.MouseClick(sender, e);
            }

            public override void MouseLeave(VirtualPanel sender, VirtualPanelMouseArgs e)
            {
                // 重置悬停状态
                if (Hover)
                {
                    SetHover(false);
                    sender.Invalidate();
                }

                // 重置链接悬停状态
                if (isUrlHover)
                {
                    isUrlHover = false;
                    sender.Invalidate();
                }

                base.MouseLeave(sender, e);
            }

            private void SetHover(bool v)
            {
                Hover = v;
            }

            public override bool MouseMove(VirtualPanel sender, VirtualPanelMouseArgs e)
            {
                // 检查鼠标是否在可交互区域
                bool isOverInteractive = closeButtonRect.Contains(e.Location) || switchRect.Contains(e.Location) || urlRect.Contains(e.Location);

                // 设置光标样式
                if (isOverInteractive)
                {
                    sender.Cursor = Cursors.Hand;
                }
                else
                {
                    sender.Cursor = Cursors.Default;
                }

                // 检查链接悬停状态变化
                bool newUrlHover = urlRect.Contains(e.Location);
                if (isUrlHover != newUrlHover)
                {
                    isUrlHover = newUrlHover;
                    sender.Invalidate();
                    return true;
                }

                // 检查悬停状态变化
                bool shouldHover = e.Rect.Contains(e.Location);
                if (Hover != shouldHover)
                {
                    SetHover(shouldHover);
                    sender.Invalidate();
                    return true;
                }

                return base.MouseMove(sender, e);
            }
        }
    }
}